//
//  OSCTweetViewControllerAnimatedTransition.m
//  OSChina
//
//  Created by 8b410-2 on 17/1/8.
//  Copyright © 2017年 abb. All rights reserved.
//

#import "OSCTweetViewControllerAnimatedTransition.h"

@implementation OSCTweetViewControllerAnimatedTransition

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.5;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    // 拿到源控制器 目标控制器 转场容器
    OSCBasePageViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    OSCTweetDetailWithBottomBarViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *container = transitionContext.containerView;
    
    // 转场动画时间
    NSTimeInterval duration = [self transitionDuration:transitionContext]/2;
    
    // 拿到选中的cell 和 其frame 生成快照view
    UIView *selectedView = fromViewController.snapshotTuple.first;
    CGRect selectedRect = [fromViewController.snapshotTuple.second CGRectValue];
    UIView *snapshotView = [selectedView snapshotViewAfterScreenUpdates:NO];
    snapshotView.frame = selectedRect;
    
    // 隐藏源控制器和目标控制器 设置目标控制器位置
    toViewController.view.frame = [transitionContext finalFrameForViewController:toViewController];
    toViewController.view.alpha = 0;
    fromViewController.tabBarController.tabBar.hidden = YES;
    fromViewController.view.alpha = 0;
    
    // 模糊遮罩创建
    UIImageView *blurView = [UIImageView new];
    UIImage *blurImage = [fromViewController.view snapshotImageAfterScreenUpdates:YES];
    blurImage = [blurImage imageByBlurDark];
    blurView.image = blurImage;
    blurView.frame = kScreen_Bounds;
    
    // 添加到转场容器
    [container addSubview:toViewController.view];
    [container addSubview:blurView];
    [container addSubview:snapshotView];
    
    // 转场动画
    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        // 移动选中cell的快照
        snapshotView.frame = CGRectMake(0, 64, snapshotView.frame.size.width, snapshotView.frame.size.height);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            // 显示目标控制器view  隐藏模糊遮罩
            toViewController.view.alpha = 1;
            blurView.alpha = 0;
            
        } completion:^(BOOL finished) {
            // 恢复源控制器透明度
            fromViewController.view.alpha = 1;
            // 移除 快照和 模糊遮罩
            [snapshotView removeFromSuperview];
            [blurView removeFromSuperview];
            // 完成转场
            [transitionContext completeTransition:YES];
        }];
    }];
}
@end
